#!/bin/bash

if [ "$#" != "3" ] && [ "$#" != "5" ]
then
	echo "Usage: test_single.bash <method> <hostname> <output file> [<input file> <credentials>]"
	exit -1
fi

method=$1
target=$2
expectedOutput=$3

if [ "$#" == "3" ]
then
	inputFile=false	
elif [ "$#" == "5" ]
then
	inputFile=$4
	credentials=$5
fi


if [ "$method" == "GET" ]
then
	curl -H "Accept: application/json" $target > tmpTestOutput 2>/dev/null
	if ! diff --ignore-tab-expansion --ignore-all-space --ignore-blank-lines --strip-trailing-cr --brief $expectedOutput tmpTestOutput >/dev/null 2>/dev/null
	then
		echo "$method AT $target *****FAILED*****"
	else
		echo "$method AT $target PASSED"
	fi
elif [ "$method" == "PUT" ]
then
	if [ "$#" == "5" ]
	then
		curl -H "Accept: application/json" -X PUT -d "`cat $inputFile`" $target > tmpTestOutput 2>/dev/null

		curl -H "Accept: application/json" $target > tmpTestOutput 2>/dev/null
		if ! diff --ignore-tab-expansion --ignore-all-space --ignore-blank-lines --strip-trailing-cr --brief $expectedOutput tmpTestOutput >/dev/null 2>/dev/null
		then
			echo "$method AT $target *****FAILED*****"
		else
			echo "$method AT $target PASSED"
		fi
	else
		echo "PUT needs DATA!"
	fi
elif [ "$method" == "DELETE" ]
then
	curl -H "Accept: application/json" -X DELETE $target > tmpTestOutput 2>/dev/null

	# was it really deleted?
	curl -H "Accept: application/json" $target > tmpTestOutput 2>/dev/null
	if ! diff --ignore-tab-expansion --ignore-all-space --ignore-blank-lines --strip-trailing-cr --brief $expectedOutput ./test_data/error_404.out >/dev/null 2>/dev/null
	then
		echo "$method AT $target *****FAILED*****"
	else
		echo "$method AT $target PASSED"
	fi
elif [ "$method" == "POST" ]
then
	if [ "$#" == "5" ]
	then
		curl -i -H "Accept: application/json" -X POST -d "`cat $inputFile`" $target > tmpTestOutput 2>/dev/null

		curl -H "Accept: application/json" $target > tmpTestOutput 2>/dev/null
		if ! diff --ignore-tab-expansion --ignore-all-space --ignore-blank-lines --strip-trailing-cr --brief $expectedOutput tmpTestOutput >/dev/null 2>/dev/null
		then
			echo "$method AT $target *****FAILED*****"
		else
			echo "$method AT $target PASSED"
		fi
	else
		echo "POST needs DATA!"
	fi
fi

